import db from "../models/index.js";
import {Op} from "sequelize";
import {clearObject, getNow} from "../utils/utils.js";

let user = db.user;
let userDao = {};

// 添加用户
userDao.addUser = async (id, user_name, email, invitation_code, inviter_id, t) => {
  let create_time = getNow();
  return user.create({
    id, user_name, email, invitation_code, inviter_id, create_time
  }, {transaction: t});
};

// 删除用户
userDao.deleteUser = async (id, t) => {
  return user.destroy({
    where: id, transaction: t
  });
};

// 查询用户 带事务锁
userDao.findUserLock = async (id, t) => {
  if (!t) {
    return user.findOne({
      where: {
        id
      },
      raw: true
    });
  }
  return user.findOne({
    where: {
      id
    }, transaction: t, lock: true, raw: true
  });
};

// 查询多个用户 带事务
userDao.findUsers = async (ids, t) => {
  return user.findAll({
    where: {
      id: {
        [Op.in]: ids
      }
    }, transaction: t, raw: true
  });
};

// 查询用户根据用户名或者邮箱
userDao.findUserByNameOrEmailOrMobile = async (user_name, email, mobile, t) => {
  return user.findOne({
    where: clearObject({user_name, email, mobile}), transaction: t, raw: true
  });
};

// 修改用户是否属于公司用户
userDao.updateUserIsCompany = async (id, is_company, t) => {
  if (!t) {
    return user.update({
      is_company
    }, {
      where: {
        id
      }
    });
  }
  return user.update({
    is_company
  }, {
    where: {
      id
    }, transaction: t
  });
};

// 修改用户手机号
userDao.updateUserMobile = async (id, mobile, t) => {
  return user.update({
      mobile
    }, {
      where: {
        id
      },
      transaction: t
    });
};

export default userDao;
